package org.kev.transit.data;

import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.httpclient.HttpException;
import org.json.JSONException;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

import org.kev.transit.TransitProvider;
import org.kev.transit.util.JsonHelper;
import org.kev.transit.util.WebHelper;
import org.kev.transit.worker.DirectionUpdateWorker;

/**
 * Direction Data Object represents a row in the Direction table
 * @author kevin
 *
 */
public class Direction implements BaseColumns {
	public static final String TABLE_NAME = "direction";
	public static final Uri CONTENT_URI = Uri.parse("content://"
			+ TransitProvider.AUTH + "/" + TABLE_NAME);

	/**
	 * The default sort order for this table
	 */
	public static final String DEFAULT_SORT_ORDER = "title DESC";

	/**
	 * The title of the direction
	 * <P>
	 * Type: TEXT
	 * </P>
	 */
	public static final String TITLE = "title";

	/**
	 * Route id
	 * <P>
	 * Type: INTEGER
	 * </P>
	 */
	public static final String ROUTE = "route";

	/**
	 * Route Type ID
	 * <P>
	 * Type: INTEGER
	 * </P>
	 */
	public static final String ROUTE_TYPE = "route_type";
	
	public static final String CREATE_DATE = "create_date";
	public static final String DIRECTION_ID = "direction_id";
	private static final String TAG ="Direction";
	//instance variables
	public String id = null;
	public String title = null;
	public String routeType=null;
	public String route=null;
	
	public long createDate;
	
	/**
	 * 
	 * @param parent calling activity
	 * @param rType id route type id
	 * @param route id
	 * @return list of direction objects
	 */
	public static final ArrayList <Direction> getData(Activity parent, String rType,String route){
		Cursor cursor=null;
		ArrayList <Direction> list = new  ArrayList <Direction>()  ;
		boolean hasData =false;
		try{
			String where = Direction.ROUTE_TYPE+"="+rType+" AND "+
			Direction.ROUTE+"="+route;
			cursor = parent.managedQuery(Direction.CONTENT_URI, new String[] {
					Direction.DIRECTION_ID,Direction.TITLE,
					Direction.ROUTE_TYPE,Direction.ROUTE}, where, null);
		
			while(cursor.next()){
				hasData=true;
				Direction dir = new Direction();
				dir.id=cursor.getString(0);
				dir.title=cursor.getString(1);
				dir.routeType=cursor.getString(2);
				dir.route=cursor.getString(3);
				list.add(dir);
			}
		}finally{
			if (cursor!=null)
				cursor.close();
		}
		if(!hasData){
			try {
				list = retrieveDataFromWeb(parent,rType,route);
			} catch (Exception e) {
				Log.e(TAG,"Unable to retrieve data from web!",e);
			} 	
		}
		
		return list;
	}
	
	/**
	 * calls web service 
	 * Returning a list of data objects.  It will then try to call
	 * a worker thread to cache the data in the locat DB
	 * @param parent calling reference
	 * @param rout type id
	 * @param route id
	 * @return list of Direction objects
	 * @throws HttpException
	 * @throws IOException
	 * @throws JSONException
	 */
	private static ArrayList <Direction> retrieveDataFromWeb(Activity parent,String rType, String route) throws HttpException, IOException, JSONException{
		Log.d(TAG,"did not find any data in tables get it from the web");
		String jsonText=null;
		jsonText=WebHelper.getDirection(rType, route);
		ArrayList <Direction> list= new ArrayList <Direction>();
		list= JsonHelper.getDirections(jsonText);
		Log.d(TAG,"Retrieved data from web="+list.size());
		/*for(int i=0;i<list.size();i++){
			Stop stop = list.get(i);
			Log.d(TAG,"stop="+stop.toXml());
		}*/

		//update db in background
		DirectionUpdateWorker worker = new DirectionUpdateWorker(parent, list);
		Thread t = new Thread(worker);
		t.start();
		//worker.run();
		return list;
	}
	
	@Override
	/**
	 * display title column
	 */
	public String toString(){
		return title;
	}
	/**
	 * dumps current instance values to a string 
	 * in a XML format
	 * @return XML
	 */
	public String toXml(){
		return
		"<"+TABLE_NAME+">\n"+
		"\t<"+Direction._ID+">"+id+"</"+Direction._ID+">\n"+
		"\t<"+Direction.TITLE+">"+title+"<"+Direction.TITLE+">\n"+
		"\t<"+Direction.ROUTE_TYPE+">"+routeType+"</"+Direction.ROUTE_TYPE+">\n"+
		"\t<"+Direction.ROUTE+">"+route+"</"+Direction.ROUTE+">\n"+
		"\t<"+Direction.CREATE_DATE+">"+createDate+"</"+Direction.CREATE_DATE+">\n"+
		"</"+TABLE_NAME+">\n" ;
	}
}
